import Cookies from "js-cookie";
import { setToken, getToken, removeToken } from "@/utils/auth";
const state = {
  routes: JSON.parse(Cookies.get("routes") || "[]"),
  authRoutes: JSON.parse(Cookies.get("authRoutes") || "[]"),
  token: getToken(),
  userInfo: JSON.parse(Cookies.get("userInfo") || "{}"),
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.routes = routes;
    Cookies.set("routes", JSON.stringify(routes));

    state.authRoutes = [];
    routes.forEach((item, index) => {
      item.children.forEach((subitem) => {
        state.authRoutes.push(subitem.routerURL);
      });
    });
    Cookies.set("authRoutes", JSON.stringify(state.authRoutes));
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
    setToken(token);
  },
  REMOVE_TOKEN: (state) => {
    state.token = undefined;
    removeToken();
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
    Cookies.set("userInfo", JSON.stringify(userInfo));
  },
  REMOVE_USERINFO: (state) => {
    state.userInfo = undefined;
    Cookies.remove("userInfo")
  },
};

export default {
  namespaced: true,
  state,
  mutations,
};
